package com.cloudcc.mobile.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;

public class SwipeLayout extends FrameLayout {
	public static final int AnimationDuring = 300;

	private boolean isOpen = false;
	
	private OnSwipeSlideListener mOnSwipeSlideListener;

	public SwipeLayout(Context context) {
		this(context, null);
	}

	public SwipeLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	private float dx;

	/**
	 * 打开侧滑菜单
	 */
	public void openMenu() {
		isOpen =true;
		getChildAt(1).setVisibility(View.VISIBLE);
		YoYo.with(Techniques.SlideInRight).duration(AnimationDuring)
				.playOn(getChildAt(1));
		if (mOnSwipeSlideListener!=null) {
			mOnSwipeSlideListener.onOpen();
			
		}
	}
	
	/**是否是打开的
	 * @return
	 */
	public boolean isOpen(){
		return isOpen;
	}
	
	
	public OnSwipeSlideListener getOnSwipeSlideListener() {
		return mOnSwipeSlideListener;
	}

	public void setOnSwipeSlideListener(OnSwipeSlideListener mOnSwipeSlideListener) {
		this.mOnSwipeSlideListener = mOnSwipeSlideListener;
	}


	public interface OnSwipeSlideListener{
		
		void onOpen();
		
		void onClose();
	}

	/**
	 * 关闭侧滑菜单
	 */
	public void closeMenu() {
		YoYo.with(Techniques.SlideOutRight).duration(AnimationDuring)
				.withListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator arg0) {
					}

					@Override
					public void onAnimationRepeat(Animator arg0) {
					}

					@Override
					public void onAnimationEnd(Animator arg0) {
						cloaseMenuWithOutAnt();
					}

					@Override
					public void onAnimationCancel(Animator arg0) {
					}
				}).playOn(getChildAt(1));

	}
	
	public void cloaseMenuWithOutAnt(){
		isOpen =false;
		getChildAt(1).setVisibility(View.VISIBLE);
		if (mOnSwipeSlideListener!=null) {
			mOnSwipeSlideListener.onClose();
			
		}
	}

	private void canSlide(MotionEvent event) {
		float cx = event.getRawX();
		float mx = cx - dx;
		if (Math.abs(cx) > 5) {
			if (mx < 0&&!isOpen) {
				openMenu();
			} else if(mx > 0&&isOpen){
				closeMenu();
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			dx = event.getRawX();
			break;
		case MotionEvent.ACTION_MOVE:
			canSlide(event);
			break;
		case MotionEvent.ACTION_UP:

			break;
		}
		return true;
	}

}
